package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func hello(i int) {
	defer wg.Done() // goroutine结束就登记-1
	fmt.Println("Hello Goroutine!", i)
}
func main() {

	//for i := 0; i < 10; i++ {
	//	wg.Add(1) // 启动一个goroutine就登记+1
	//	go hello(i)
	//}
	//wg.Wait() // 等待所有登记的goroutine都结束

	// 互斥锁
	wg.Add(2)
	go add()
	go add()
	wg.Wait()
	fmt.Println(x)
}

var x int64
var lock sync.Mutex

func add() {
	for i := 0; i < 5000; i++ {
		lock.Lock() // 加锁
		x = x + 1
		lock.Unlock() // 解锁
	}
	wg.Done()
}
